<!--  -->
<template>
  <div class="pages-data-table">
    <el-table v-loading="loading" :data="data" style="width: 100%">
      <el-table-column prop="name" label="页面名称">
        <template slot-scope="scope">
          <i :class="'noselect icon iconfont ' + showIcon(scope.row.id, scope.row.index)"
            @click="tiggleChildren(scope.row.id)" :style="'margin-left: '+rowMaringLeft(scope.row.index)+'px'"></i>
          <span style="margin-left: 10px">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" width="180" align="center">
        <template slot-scope="scope">
          <OrderPage :id="scope.row.id" :data="initRequestData" :list="list" :updateDataOrder="updateDataOrder" />
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" width="100" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.type === 1">普通页面</span>
          <span v-if="scope.row.type === 2" class="green">系统页面</span>
          <span v-if="scope.row.type === 3" class="orange">外链接页面</span>
          <span v-if="scope.row.type === 4" class="orange">内链接页面</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="页面显示" width="120" align="center">
        <template slot-scope="scope">
          <el-switch v-model="operatData[scope.row.id].status" active-color="#13ce66"
            @change="changeStatus(scope.row.id, operatData[scope.row.id].status)">
          </el-switch>
          <span
            style="line-height: 1;font-size: 14px;display: inline-block;color:#666666;">&nbsp;{{operatData[scope.row.id].status?'显示':'隐藏'}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="hide" label="导航中显示" width="120" align="center">
        <template slot-scope="scope">
          <el-switch v-model="operatData[scope.row.id].hide" active-color="#13ce66"
            @change="changeHide(scope.row.id, operatData[scope.row.id].hide)" :disabled="!operatData[scope.row.id].status">
          </el-switch>
          <span
            style="line-height: 1;font-size: 14px;display: inline-block;color:#666666;">&nbsp;{{operatData[scope.row.id].hide?'显示':'隐藏'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" align="center">
        <template slot-scope="scope">
          <el-button @click="handleClick(scope.row)" type="text" size="small"
            v-if="currentRoles.design && scope.row.type !== 3 && scope.row.type !== 4 && operatData[scope.row.id].status">
            设计</el-button>
          <el-button @click="windowOpen(scope.row.id)" type="text" size="small">查看</el-button>
          <el-button @click="editorPageSeo(scope.row.id)" type="text" size="small">SEO</el-button>
          <el-button @click="editorPage(scope.row.id)" type="text" size="small">编辑</el-button>
          <el-button @click="copyPage(scope.row.id, scope.row.type, scope.row.name)" type="text" size="small">复制</el-button>
          <el-button @click="deletePage(scope.row.id)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <SavePage ref="editPage" :propsOnSubmit="onSubmit" />
    <SeoPageDialog ref="seoPageDialog" />
    <CopyPageDialog ref="copyPageDialog" :propsOnSubmit="onSubmit" />
  </div>
</template>

<script>
import * as DesignFunctions from '@/core/DesignFunctions.js'
import OrderPage from '@/components/main/user/pages/common/OrderPage.vue'
// import SavePage from '@/components/main/user/pages/common/SavePage.vue'
import SavePage from '@/components/common/design/dialog/page/editor/SavePage.vue'
import SeoPageDialog from '@/components/main/user/siteseo/common/SeoPageDialog.vue'
import CopyPageDialog from '@/components/common/design/dialog/page/editor/CopyPageDialog.vue'
import { mapGetters } from 'vuex'
import * as functions from '@/core/functions.js'
export default {
  props: {
    // 改变加载数据的loading属性
    changeDataLoading: {
      type: Function
    },
    // 回写数据总数
    totalPage: {
      type: Function
    },
    loading: {
      type: Boolean
    }
  },
  created () {
    this.initData()
  },
  data () {
    return {
      // 初始显示表格数据
      initRequestData: [],
      // 表格显示数据
      data: [],
      // 原始数据
      pagedata: [],
      // 操作分级，以及子集是否显示数据
      operatData: {}
    }
  },
  computed: {
    ...mapGetters(['currentRoles']),
    // 过滤数据
    list () {
      let list = []
      for (let i in this.initRequestData) {
        list.push({
          id: this.initRequestData[i].id,
          parentId: this.initRequestData[i].parentId,
          orderNum: this.initRequestData[i].orderNum,
          type: this.initRequestData[i].type
        })
      }
      return list
    }
  },
  watch: {
    // 一旦pageData改变则重新加载数据表显示的数据
    pagedata: {
      handler () {
        this.initRequestData = this.data = initResponsePageData(this.pagedata)
        this.operatData = initResponsePageOperatData(this.pagedata)
      },
      deep: true
    }
  },
  methods: {
    onSubmit () {
      this.resetData()
    },
    initData () {
      this.$post('/page/infos', null).then(response => {
        if (response && response.total) {
          this.pagedata = response.pages
          this.totalPage(response.total)
        } else {
          this.pagedata = []
          this.totalPage(0)
        }
        this.changeDataLoading(false)
      })
    },
    resetData () {
      this.changeDataLoading(true)
      this.initData()
    },
    tiggleChildren (id) {
      let operatData = JSON.parse(JSON.stringify(this.operatData))
      operatData[id].childrenShow = !operatData[id].childrenShow
      this.operatData = operatData
      this.data = tiggleChildrenPageData(this.pagedata, this.operatData)
    },
    showIcon (id, index) {
      // 如果没有子级则 icon-wendubukediao
      if (index === 2) {
        return 'icon-wendubukediao'
      }
      if (this.operatData[id]) {
        if (this.operatData[id].children) {
          if (this.operatData[id].childrenShow) {
            return 'icon-iconfontarrowdown'
          } else {
            return 'icon-iconfontplayfill'
          }
        }
      }
    },
    editorPageSeo (id) {
      this.$refs['seoPageDialog'].show(id)
    },
    copyPage (id, type, name) {
      this.$refs['copyPageDialog'].show(id, type, name, true)
    },
    rowMaringLeft (index) {
      if (index === 0) {
        return 0
      }
      let result = 15
      for (let i = 0; i < index; i++) {
        result += 15
      }
      return result
    },
    changeStatus (id, status) {
      this.$post('/page/change-status', {
        id: id,
        status: status ? 1 : 0
      }).then(response => {
        this.resetData()
      }
      )
    },
    changeHide (id, hide) {
      this.$post('/page/change-hide', {
        id: id,
        hide: hide ? 0 : 1
      }).then(response => {
        this.resetData()
      }
      )
    },
    // handleClick (id) {
    //   const loading = this.$loading({
    //     lock: true,
    //     text: '正在打开...',
    //     spinner: 'el-icon-loading',
    //     background: 'rgba(0, 0, 0, 0.7)'
    //   })
    //   this.$post('/navigation/infos', {index: '2'}).then(response => {
    //     let pageCur = []
    //     for (let i in response) {
    //       if (response[i].pageId === id) {
    //         pageCur.push(response[i])
    //       } else if (response[i].children && response[i].children.length > 0) {
    //         for (let j in response[i].children) {
    //           if (response[i].children[j].pageId === id) {
    //             pageCur.push(response[i].children[j])
    //           } else if (response[i].children[j].children && response[i].children[j].children.length > 0) {
    //             for (let k in response[i].children[j].children) {
    //               if (response[i].children[j].children[k].pageId === id) {
    //                 pageCur.push(response[i].children[j].children[k])
    //               }
    //             }
    //           }
    //         }
    //       }
    //     }
    //     if (!pageCur) {
    //       return
    //     }
    //     let result = functions.routerPush('/backend/design')
    //     this.$router.push(result)
    //     let src = DesignFunctions.getDesignPath(this.$store.state.host.id, this.$store.state.site.site.id, pageCur[0].link)
    //     this.$store.dispatch('designSetIframeSrc', src)
    //     loading.close()
    //   })
    // },
    handleClick (item) {
      const loading = this.$loading({
        lock: true,
        text: '正在打开...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      let result = functions.routerPush('/backend/design')
      this.$router.push(result)
      let src = DesignFunctions.getDesignPath(this.$store.state.host.id, this.$store.state.site.site.id, item.link)
      this.$store.dispatch('designSetIframeSrc', src)
      loading.close()
    },
    windowOpen (id) {
      const loading = this.$loading({
        lock: true,
        text: '正在打开...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.$post('/url/page-link', {
        id: id
      }).then(response => {
        loading.close()
        if (response) {
          window.open(response, '_blank')
        }
      }, () => {
        loading.close()
      })
    },
    editorPage (id) {
      let page
      for (let i in this.pagedata) {
        for (let j in this.pagedata[i]) {
          let temp = this.pagedata[i][j]
          if (temp.id === id) {
            page = temp
            break
          }
        }
      }
      if (page) {
        // 编辑页面
        this.$refs['editPage'].show(page, '编辑页面-' + page.name, true)
      }
    },
    deletePage (id) {
      this.$confirm('确认要删除？', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.$post('/page/delete', {
            id: id
          }).then((response) => {
            if (response && response.error) {

            } else {
              this.resetData()
            }
          })
        })
        .catch(() => {
        })
    },
    updateDataOrder (data, propid) {
      // 更新排序数据
      let update = []
      for (let k in data) {
        let dat = data[k]
        for (let i in this.pagedata) {
          for (let j in this.pagedata[i]) {
            let temp = this.pagedata[i][j]
            if (temp.id === dat.id) {
              let _temp = JSON.parse(JSON.stringify(temp))
              _temp.parentId = dat.parentId
              _temp.orderNum = dat.orderNum
              update.push(_temp)
            }
          }
        }
      }
      this.$jpost('/page/update-order/' + propid, update).then(response => {
        this.resetData()
      })
    }
  },
  components: {
    OrderPage,
    SavePage,
    SeoPageDialog,
    CopyPageDialog
  }
}

function initResponsePageData (data) {
  if (!data) {
    return []
  }
  let result = []
  let topData = data[0]
  for (let i in topData) {
    let topItem = topData[i]
    let link1 = ''
    if (topItem.type === 3 || topItem.type === 4) {
      link1 = topItem.url
    } else {
      link1 = '/' + topItem.rewrite + '.html'
    }
    result.push({
      index: 0,
      id: topItem.id,
      parentId: topItem.parentId,
      name: topItem.name,
      type: topItem.type,
      status: topItem.status,
      orderNum: topItem.orderNum,
      hide: topItem.hide,
      link: link1
    })
    for (let j in data[topItem.id]) {
      let item = data[topItem.id][j]
      let link2 = ''
      if (item.type === 3 || item.type === 4) {
        link2 = item.url
      } else {
        link2 = '/' + item.rewrite + '.html'
      }
      result.push({
        index: 1,
        id: item.id,
        parentId: item.parentId,
        name: item.name,
        type: item.type,
        status: item.status,
        orderNum: item.orderNum,
        hide: item.hide,
        link: link2
      })
      for (let k in data[item.id]) {
        let ite = data[item.id][k]
        let link3 = ''
        if (ite.type === 3 || ite.type === 4) {
          link3 = ite.url
        } else {
          link3 = '/' + ite.rewrite + '.html'
        }
        result.push({
          index: 2,
          id: ite.id,
          parentId: ite.parentId,
          name: ite.name,
          type: ite.type,
          status: ite.status,
          orderNum: ite.orderNum,
          hide: ite.hide,
          link: link3
        })
      }
    }
  }
  return result
}

function initResponsePageOperatData (data) {
  let result = {}
  for (let i in data) {
    for (let j in data[i]) {
      let item = data[i][j]
      let children = false
      if (data[item.id]) {
        children = true
      }
      result[item.id] = {
        children: children,
        childrenShow: true,
        status: item.status > 0,
        hide: item.hide < 1
      }
    }
  }
  return result
}

function tiggleChildrenPageData (pagedata, operatData) {
  if (!pagedata) {
    return []
  }
  let result = []
  let topData = pagedata[0]
  for (let i in topData) {
    let topItem = topData[i]
    result.push({
      index: 0,
      id: topItem.id,
      parentId: topItem.parentId,
      name: topItem.name,
      type: topItem.type,
      status: topItem.status,
      orderNum: topItem.orderNum,
      hide: topItem.hide
    })
    // 是否有子级
    if (pagedata[topItem.id]) {
      // 子级中的数据是否显示
      if (operatData[topItem.id] && !operatData[topItem.id].childrenShow) {
        continue
      }
    }
    for (let j in pagedata[topItem.id]) {
      let item = pagedata[topItem.id][j]
      result.push({
        index: 1,
        id: item.id,
        parentId: item.parentId,
        name: item.name,
        type: item.type,
        status: item.status,
        orderNum: item.orderNum,
        hide: item.hide
      })
      // 是否有子级
      if (pagedata[item.id]) {
        // 子级中的数据是否显示
        if (operatData[item.id] && !operatData[item.id].childrenShow) {
          continue
        }
      }
      for (let k in pagedata[item.id]) {
        let ite = pagedata[item.id][k]
        result.push({
          index: 2,
          id: ite.id,
          parentId: ite.parentId,
          name: ite.name,
          type: ite.type,
          status: ite.status,
          orderNum: ite.orderNum,
          hide: ite.hide
        })
      }
    }
  }
  return result
}
</script>

<style scoped>
.icon {
  cursor: pointer;
}
.icon:hover {
  color: #409eff;
}
.icon-wendubukediao{
 cursor: default;
}
.pages-data-table /deep/ .el-table th {
  color: #555;
}
</style>
